<template>
  <div>
    <ping :ping="ping" @guanbi="pingguanbi($event)"></ping>
    <div class="tree-box moreLine" :style="{ paddingBottom: transferHeight.pb + 'px' }">
      <div>
        <span>设备所在辖区</span>
        <treesBox :treesBox="treesBox" @handleNodeClick="treeClick($event)"></treesBox>
      </div>
    </div>
    <div class="main_r" :style="{ minHeight: transferHeight.contentH + 'px' }">
      <!-- Echarts 图标 -->
      <div class="t">
        <el-row class="t_container">
          <el-col :span="12">
            <echarts-load v-if="pieFlag || reload_pie" :chartFlag="pieFlag" :reload="reload_pie" @refreshF="refreshPie" />
            <gzkz-pie v-else :pieData="pieData" />
          </el-col>
          <el-col :span="12">
            <echarts-load v-if="barFlag || reload_bar" :chartFlag="barFlag" :reload="reload_bar" @refreshF="refreshBar" />
            <gzkz-bar v-else :barData="barData" />
          </el-col>
        </el-row>
      </div>
      <div class="b">
        <!-- 搜索条件 -->
        <el-form :inline="true" :model="searchCriteria" class="demo-form-inline">
          <el-form-item label="设备类型:">
            <!-- <el-select
              v-model="searchCriteria.typeVal"
              class="inputWidth"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in zicanOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>-->
            <el-cascader class="inputWidth" v-model.trim="searchCriteria.typeVal" :options="zicanOptions" :props="{ checkStrictly: true }" filterable clearable></el-cascader>
          </el-form-item>
          <!-- <el-form-item label="故障类型:">
            <el-select v-model="searchCriteria.isGZ" class="inputWidth" clearable placeholder="请选择">
              <el-option label="未生成" value="0"></el-option>
              <el-option label="已生成" value="1"></el-option>
            </el-select>
          </el-form-item>-->
          <!-- <el-form-item label="报障时间:">
            <el-date-picker
              v-model="searchCriteria.dataTime"
              :picker-options="pickerBeginDateBefore"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>-->
          <el-form-item>
            <el-input v-model.trim="searchCriteria.namer" width="200" prefix-icon="el-icon-search" clearable placeholder="输入设备名称或设备IP"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" class="btnSizeStyle">查询</el-button>
          </el-form-item>
        </el-form>
        <!-- 表格 -->
        <el-table
          :header-cell-style="{ backgroundColor: '#ECF3FC', color: '#333', height: '48px', borderBottom: '1px solid #CEE1F7' }"
          :cell-class-name="addClass"
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          border
          highlight-current-row
          stripe
          @sort-change="sortthiscolumn"
          v-loading="tableLoad"
          :header-row-style="{ height: '28px' }"
        >
          <!-- 序号 -->
          <el-table-column type="index" min-width="50" label="序号" align="center"></el-table-column>
          <!-- 提示语句 -->
          <template slot="empty">{{ tableMessage }}</template>
          <el-table-column class="xxxx1" prop="zcmc" label="设备名称" sortable :show-overflow-tooltip="true" min-width="200">
            <template slot-scope="scope">
              <!-- <el-tooltip class="item" content="异常" placement="top-start" popper-class="atooltip"> -->
              <svg class="iconfont" aria-hidden="true">
                <use xlink:href="#el-icon-myfault1" style="font-size: 50px" />
              </svg>
              <!-- </el-tooltip> -->
              <span v-html="getzcmc(scope.row)"></span>
            </template>
          </el-table-column>
          <el-table-column prop="zclxmc" label="设备类型" min-width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-html="getsblx(scope.row)"></span>
            </template>
          </el-table-column>
          <el-table-column label="安装地址" min-width="250" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.zcsfmc + scope.row.zccsmc + scope.row.zcqxmc + scope.row.zcjdmc + scope.row.xxdz }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ip" label="设备IP" min-width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.ip }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="wtlxmc" label="故障数" min-width="100">
            <template slot-scope="scope">
              <span class="haveLinks" @click="gzXiangqing(scope.row)">{{ scope.row.counts }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="zclxmc" label="品牌" min-width="80">
            <template slot-scope="scope">
              <span>{{ scope.row.ppmc }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="zclxmc" label="型号" min-width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.xh }}</span>
            </template>
          </el-table-column>
          <el-table-column label="宿主" min-width="98">
            <template slot-scope="scope">
              <span v-for="(item, index) in scope.row.szs" :key="index">
                <el-tooltip v-if="Number(item.SZLX) >= 0" class="item" placement="top-start" popper-class="atooltip">
                  <div slot="content">{{ item.SZMC }}</div>
                  <svg class="iconfont" aria-hidden="true" style="width: 20px; height: 20px">
                    <!-- 0运维主机 1卡口 2电警 -->
                    <use :xlink:href="`#el-icon-mysuzhu_${item.SZLX}`" style="font-size: 50px" />
                  </svg>
                </el-tooltip>
                <svg v-else class="iconfont" aria-hidden="true" style="width: 20px; height: 20px">
                  <!-- 0运维主机 1卡口 2电警 -->
                  <use :xlink:href="`#el-icon-my${grayIcon[index]}`" style="font-size: 50px" />
                </svg>
              </span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="bzsj" label="报障时间" sortable="custom" min-width="150">
            <template slot-scope="scope">
              <span>{{scope.row.bzsj | dateFormat}}</span>
            </template>
          </el-table-column>-->
          <!-- <el-table-column prop="wtlx" label="工单状态" min-width="120">
            <template slot-scope="scope">
              <span
                :class="[`type${Number(scope.row.gdzt)}`,'type']"
              >{{type[Number(scope.row.gdzt)]}}</span>
            </template>
          </el-table-column>-->
          <el-table-column fixed="right" label="操作" min-width="150" align="right">
            <template slot-scope="scope">
              <div class="operations">
                <!-- 不可以点击加上 noAction这个类名 -->
                <!-- <el-button type="text" @click="handleClick(scope.row)">编辑</el-button> -->
                <el-button type="text" :disabled="scope.row.ip !== '' && scope.row.ip !== null ? false : true" class="Btn_nan" @click="yuanChenKZ(scope.row)">远程控制</el-button>
                <span class="operation"></span>
                <el-button type="text" @click="showPingOk(scope.row)" :disabled="scope.row.ip !== '' && scope.row.ip !== null ? false : true">ping</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row class="page-row fooer_box">
          <el-col :span="12">
            <div class="bigBOx btnBefore">
              <div class="imgBox">
                <svg class="iconfont imgIcon" aria-hidden="true">
                  <use xlink:href="#el-icon-myfault1" />
                </svg>
                <span>异常</span>
              </div>
              <div class="imgBox">
                <svg class="iconfont imgIcon size17" aria-hidden="true">
                  <use xlink:href="#el-icon-mysuzhu_0" />
                </svg>
                <span>运维主机</span>
              </div>
              <div class="imgBox">
                <svg class="iconfont imgIcon size17" aria-hidden="true">
                  <use xlink:href="#el-icon-mysuzhu_1" />
                </svg>
                <span>卡口</span>
              </div>
              <div class="imgBox">
                <svg class="iconfont imgIcon size17" aria-hidden="true">
                  <use xlink:href="#el-icon-mysuzhu_2" />
                </svg>
                <span>电子警察</span>
              </div>
            </div>
          </el-col>
          <el-col :span="12" style="height: 47px; display: table">
            <!-- <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[1, 5, 10, 15]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next"
              :total="total"
            ></el-pagination> -->
            <!-- @size-change="handleSizeChange" -->
            <el-pagination
              background
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              @size-change="handleSizeChange"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total,sizes,prev, pager, next"
              :total="total"
            ></el-pagination>
          </el-col>
        </el-row>
      </div>
    </div>
    <countList :countListData="countListData"></countList>
  </div>
</template>
<script>
import gzkzPie from '@/components/Echarts/gzkzPie'
import gzkzBar from '@/components/Echarts/gzkzBar'
import { getUrl } from '@/utils/getUrl.js'
import { yeWu, ziC } from '@/utils/allUrl'
import Ping from '@/components/ping/index.vue'
import treesBox from '@/components/treesBox/index.vue'
import { timeLoad, tableMessageText } from '@/assets/js/setTime'
import echartsLoad from '@/components/Echarts/echartsLoad'
import countList from '@/components/RunTesting/countList.vue'
import { threeLevelH } from '@/assets/js/calcHeight'

export default {
  computed: {
    transferHeight: function () {
      //   // 计算屏幕滚动高度 - nav - 导航栏
      return {
        contentH: window.innerHeight - threeLevelH,
        pb: threeLevelH,
      }
    },
  },
  components: { gzkzPie, gzkzBar, Ping, treesBox, echartsLoad, countList },
  data: function () {
    return {
      //  1 '已受理 (',当前处理人可看)
      //  2 '待确认',
      //  3 '正常关闭',
      //  4 '驳回',
      //  5 '挂起',
      //  6 '外派',
      //  7 '异常关闭',
      // type: ['未生成', '已受理', '待确认', '正常关闭', '驳回', '挂起', '外派', '异常关闭'], // 正常和异常关闭不需要
      ping: {
        // ping
        name: '', // ping设备名称
        speedOpen: false, // ping框
        ip: '',
      },
      treesBox: {
        // url: 'yonghu/selectYongHuXiaQuByGzjs',
        url: 'ZI_CHAN',
        GZKZ: false,
      }, // tree图的请求地址
      zicanOptions: [], // 资产类型
      searchCriteria: {
        typeVal: '', // 设备类型
        // isGZ: '0', // 故障类型
        // dataTime: '', // 报障时间
        namer: '',
      },
      tableData: [], // 列表
      wtbmdjs: 1,
      // pickerBeginDateBefore: {
      //   // 设置只能选择到今天及以前的日期
      //   disabledDate(time) {
      //     return time.getTime() >= Date.now()
      //   }
      // },
      kuaizhao: 0, // 快照时间
      listQuery: {
        sortby: '',
        order: '',
      },
      currentPage: 1, // 页码
      total: 0, // 总条数
      pageSize: 10, // 每页显示的条目数
      pieFlag: false, // 环形图
      barFlag: false,
      pieData: [], // 环形图数据
      barData: {}, // 柱状图数据
      tableLoad: false, // 表格加载中样式
      city: '',
      cityLevel: 0,
      tableMessage: '',
      tableTimer: null,
      pieTimer: null,
      barTimer: null,
      reload_pie: false,
      reload_bar: false,
      countListData: {
        type: '设备',
        url: 'gz/selectById',
        xianqingID: '', // 详情ID
        contractDialogVisible: false,
        contractDetailList: [], // 故障详情
      },
      grayIcon: ['zhuji_hui', 'kakou_hui', 'dzjc_hui'],
    }
  },
  watch: {
    tableLoad(newVal, oldVal) {
      this.tableTimer = setTimeout(() => {
        if (this.tableLoad) {
          this.tableLoad = false
          this.tableData = []
          this.tableMessage = tableMessageText
          // this.total = 0
        }
      }, timeLoad)
    },
    pieFlag(newVal, oldVal) {
      this.pieTimer = setTimeout(() => {
        if (this.pieFlag) {
          this.pieFlag = false
          this.reload_pie = true
        }
      }, timeLoad)
    },
    barFlag(newVal, oldVal) {
      this.barTimer = setTimeout(() => {
        if (this.barFlag) {
          this.barFlag = false
          this.reload_bar = true
        }
      }, timeLoad)
    },
  },
  created() {
    this.initPie() // 饼状图
    this.initBar() // 柱状图
    // this.treeData = JSON.parse(getUrl('xiaquCity'))
    this.initGzlx() // 故障类型
    this.initList()
  },
  mounted() {},
  methods: {
    getzcmc(row) {
      return row.zcmc
    },
    getsblx(row) {
      return `<span>${row.zclxmc1 ? row.zclxmc1 + ' / ' : ''}</span>
                <span>${row.zclxmc2 ? row.zclxmc2 + ' / ' : ''}</span>
                <span>${row.zclxmc3}</span>`
    },
    async initList() {
      clearTimeout(this.tableTimer)
      this.tableLoad = true
      const params = new URLSearchParams()
      params.append('userId', JSON.parse(getUrl('userconter')).id) // 当前用户ID
      // params.append('GZKZ', 'a') // 查询故障快照列表(随便传一个值)
      params.append('order', this.listQuery.sortby) // 排序字段
      params.append('sort', this.listQuery.order) // DESC降序 ASC升序
      params.append('M_', this.currentPage) // 当前页
      params.append('N_', this.pageSize) // 每页显示行数
      params.append('zclx', this.searchCriteria.typeVal[this.searchCriteria.typeVal.length - 1] || '') // 资产类型ID
      params.append('zcmc', this.searchCriteria.namer) // 设备名称,IP条件
      switch (this.cityLevel) {
        case 1:
          params.append('SF', this.city)
          break
        case 2:
          params.append('CS', this.city)
          break
        case 3:
          params.append('QX', this.city)
          break
        case 4:
          params.append('XZJD', this.city)
          break
        default:
      }
      // if (Array.isArray(this.searchCriteria.dataTime)) {
      //   params.append('BZSJS', this.searchCriteria.dataTime[0]) // 报障时间-开始时间
      //   params.append('BZSJE', this.searchCriteria.dataTime[1]) // 报障时间-结束时间
      // }
      const { data: res } = await this.$http.post(yeWu + 'gz/selectGuZhangGroup', params)
      switch (res.code) {
        case '0000': // 操作成功
          this.tableData = res.data.list
          this.total = res.data.total
          break
        default:
          this.tableData = []
          this.total = 0
          this.tableMessage = res.message
          break
      }
      this.tableLoad = false // 表格加载中样式
    },
    async initGzlx() {
      // 设备类型
      // const params = new URLSearchParams()
      // params.append('FLBISNULL', 0)
      // const { data: res } = await this.$http.post(yeWu + 'wtgzzd/selectWenTiGuZhangZiDian', params)
      // if (res.code === '0014') {
      //   return ''
      // } else if (res.code !== '0000') {
      //   return this.$message({
      //     type: 'error',
      //     message: res.message,
      //     center: true
      //   })
      // }
      // res.data.list.forEach(item => {
      //   const k = {
      //     value: item.id,
      //     label: item.lbmc
      //   }
      //   this.zicanOptions.push(k)
      // })
      const params = new URLSearchParams()
      params.append('FLXID', 0)
      const { data: res } = await this.$http.post(`${ziC}zczd/list`, params)
      const city = JSON.stringify(res.data.list)
      const newCity = city.replace(/id/g, 'value')
      const cityList = newCity.replace(/lxmc/g, 'label')
      this.zicanOptions = JSON.parse(cityList)
    },
    // 环形图
    async initPie() {
      clearTimeout(this.pieFlag)
      this.pieFlag = true
      const { data: res } = await this.$http.post(yeWu + 'gz/selectTBSJ')
      this.pieFlag = false
      var arr = []
      switch (res.code) {
        case '0000':
          arr = [
            { value: res.data.ZC_, name: '正常' },
            { value: res.data.YC_, name: '故障' },
          ]
          this.pieData = arr
          break
        case '0013': // 暂无数据
          arr = [
            { value: 0, name: '正常' },
            { value: 0, name: '故障' },
          ]
          this.pieData = arr
          break
        default:
          this.reload_pie = true
          break
      }
    },
    // 柱状图
    async initBar() {
      clearTimeout(this.barTimer)
      this.barFlag = true
      const arr1 = []
      const arr2 = []
      const { data: res } = await this.$http.post(yeWu + 'gz/selectGzlbCount')
      this.barFlag = false
      switch (res.code) {
        case '0000':
          res.data.list.forEach((item) => {
            arr1.push(item.lxmc)
            arr2.push(item.count)
          })
          this.barData = { arr1: arr1, arr2: arr2 }
          break
        case '0013':
          this.barData = { arr1: ['电力', '通讯', '安装集成', '软件', '设备本体', '配置', '机房动环'], arr2: [0, 0, 0, 0, 0, 0, 0] }
          break
        default:
          this.reload_bar = true
          break
      }
    },
    refreshPie() {
      this.reload_pie = false
      this.initPie()
    },
    refreshBar() {
      this.reload_bar = false
      this.initBar()
    },
    // 设备所在辖区
    treeClick(e) {
      this.tableLoad = true // 表格加载中样式
      this.city = e.type.label
      this.cityLevel = e.type.levels
      this.currentPage = 1 // 重置页码
      this.pageSize = 10 // 重置每页页数
      this.initList()
    },
    // 提交按钮
    onSubmit: function () {
      this.tableLoad = true
      this.currentPage = 1 // 页码
      this.pageSize = 10 // 每页显示的条目数
      this.initList()
    },
    handleSizeChange(val) {
      // 切换每页显示
      this.currentPage = 1 // 页码
      this.pageSize = val
      this.initList()
      // const userId = JSON.parse(getUrl('userconter')).id
    },
    handleCurrentChange(val) {
      this.tableLoad = true // 加载中样式
      this.currentPage = val
      this.initList()
    },
    sortthiscolumn(column) {
      // 排序
      // console.log(column)
      this.tableLoad = true // 加载中样式
      if (column.order === 'descending') {
        this.listQuery.sortby = column.prop.toUpperCase()
        this.listQuery.order = 'DESC' // 降序
      } else if (column.order === 'ascending') {
        this.listQuery.sortby = column.prop.toUpperCase()
        this.listQuery.order = 'ASC' // 升序
      } else {
        this.listQuery.sortby = ''
        this.listQuery.order = '' // 没有排序
      }
      this.initList()
    },
    yuanChenKZ(scope) {
      if (scope.ZCLXMC === '运维主机' && scope.ZCLX === 53) {
        // this.$router.push('/mainboard')
        localStorage.setItem('SN', scope.sbxlh)
        localStorage.setItem('password', scope.dlmm)
        localStorage.setItem('IP', scope.ip)
        localStorage.setItem('XQBM', scope.zcxqbm)
        sessionStorage.setItem('mianUrl', '')
        localStorage.setItem('zcmc', scope.zcmc)
        this.$router.push({ name: 'mainboaredit' })
      } else {
        window.open('http://' + scope.ip, '_blank')
      }
    },
    // ping
    showPingOk(val) {
      this.ping.speedOpen = true
      this.ping.ip = val.ip
      this.ping.name = val.zcmc
    },
    // ping组件
    pingguanbi(val) {
      this.ping = {
        speedOpen: val.type,
        name: '', // ping设备名称
        ip: '',
      }
    },
    addClass({ row, column, rowIndex, columnIndex }) {
      // table添加样式
      // console.log('row:', row, 'column:', column, 'rowIndex:', rowIndex, 'columnIndex:', columnIndex)
      // if (columnIndex === 0) {
      // return 'fontColor'
      // }
    },
    gzXiangqing(val) {
      this.countListData.contractDetailList = val
      this.countListData.contractDialogVisible = true
      this.countListData.xianqingID = val.id
      // this.huoquxiangqing()
    },
  },
  destroyed() {
    // clearTimeout(timeBox)
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/scss/xjzxCommon.scss';
// .dialogText {
//   font-size: 14px;
//   color: #333;
//   .star {
//     color: #f56c6c;
//   }
//   .contentFont {
//     display: inline-block;
//     width: 120px;
//     color: #7a7a7a;
//     text-align: right;
//   }
//   .lineHight .el-row {
//     line-height: 30px;
//   }
// }
.footerPagination {
  display: flex;
  justify-content: space-between;
}
.t_container {
  height: 100%;
  .el-col {
    height: 100%;
  }
}
</style>
